# -*- coding: utf-8 -*-
from app.api.service import agv_service
from app.common.exception.agv import AGVError
from app.common.response.response_schema import response_base
from app.core.conf import ST
from app.schemas.agv import RQAGV
from fastapi import APIRouter
from loguru import logger
from sio_agv.agv_socket import AGV

agv_router = APIRouter()


@agv_router.post("/status", summary="status接口")
async def status_agv(obj: RQAGV):
    tt15 = AGV.get_agv(ST.AGV_IP)
    tt15.send("status", obj.m_num, obj.m_type, obj.m_data)
    res = tt15.receive("status")
    if res.get("ret_code"):
        raise AGVError(res)
    return response_base.response_200(msg="执行成功", data=res)


@agv_router.get("/battery", summary="电池接口")
async def get_battery_info():
    tt15 = AGV.get_agv(ST.AGV_IP)
    tt15.send("status", 1, 1007)
    res = tt15.receive("status")
    if res.get("ret_code"):
        raise AGVError(res)
    return response_base.response_200(msg="查询成功", data=res)


@agv_router.post("/control", summary="control接口")
async def control_agv(obj: RQAGV):
    tt15 = AGV.get_agv(ST.AGV_IP)
    tt15.send("control", obj.m_num, obj.m_type, obj.m_data)
    res = tt15.receive("control")
    if res.get("ret_code"):
        raise AGVError(res)
    return response_base.response_200(msg="执行成功", data=res)


@agv_router.post("/nav", summary="nav接口")
async def nav_agv(obj: RQAGV):
    tt15 = AGV.get_agv(ST.AGV_IP)
    tt15.send("nav", obj.m_num, obj.m_type, obj.m_data)
    res = tt15.receive("nav")
    if res.get("ret_code"):
        raise AGVError(res)
    return response_base.response_200(msg="执行成功", data=res)


@agv_router.post("/config", summary="config接口")
async def config_agv(obj: RQAGV):
    tt15 = AGV.get_agv(ST.AGV_IP)
    tt15.send("config", obj.m_num, obj.m_type, obj.m_data)
    res = tt15.receive("config")
    if res.get("ret_code"):
        raise AGVError(res)
    return response_base.response_200(msg="执行成功", data=res)


@agv_router.post("/other", summary="other接口")
async def other_agv(obj: RQAGV):
    tt15 = AGV.get_agv(ST.AGV_IP)
    tt15.send("other", obj.m_num, obj.m_type, obj.m_data)
    res = tt15.receive("other")
    if res.get("ret_code"):
        raise AGVError(res)
    return response_base.response_200(msg="执行成功", data=res)


@agv_router.get("/map", summary="获取地图")
async def map_agv(map_type: str):
    res = await agv_service.get_agv_map(map_type)
    return response_base.response_200(msg="执行成功", data=res)


@agv_router.get("/start", summary="启动AGV任务链接")
async def start_connect_agv():
    await agv_service.start_agv_task()
    return response_base.response_200(msg="执行成功", data="启动重新连接")
